package com.dueeeke.videoplayer.aplayer;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

import com.aplayer.APlayerAndroid;
import com.dueeeke.videoplayer.player.AbstractPlayer;

import java.util.Map;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

public class APlayer extends AbstractPlayer {
    private final Context mAppContext;
    private APlayerAndroid aPlayer;
    private int mBufferedPercent;
    private String path;

    public APlayer(Context context) {
        mAppContext = context;
    }

    @Override
    public void initPlayer() {
        aPlayer = new APlayerAndroid();
        setOptions();
        aPlayer.setOnPlayCompleteListener(onPlayCompleteListener);
        aPlayer.setOnBufferListener(onBufferListener);
        aPlayer.setOnOpenCompleteListener(onOpenCompleteListener);
        //设置画面模式
        /*“0” 默认模式，在保持纵横比的情况下，如果视频的宽高比大于窗口的宽高比则视频宽顶边， 否则高顶边。
“1” 裁剪模式，视频宽高比大于窗口宽高比的情况，视频的高顶边，宽裁剪两边，以保持纵 横比。反之，宽顶边，裁剪高度。
“2”拉伸模式，视频铺满窗口并且不裁剪，如果窗口宽高比不等于视频的宽高比 视频会出现 拉伸现象。*/
        //aPlayer.setConfig(APlayerAndroid.CONFIGID.STRETCH_MODE,"0");
    }

    @Override
    public void setDataSource(String path, Map<String, String> headers) {
        StringBuilder stringBuilder = new StringBuilder();
        //处理UA问题
        if (headers != null) {
            for (String key : headers.keySet()) {
                String userAgent = headers.get("User-Agent");
                if (!TextUtils.isEmpty(userAgent)) {
                    aPlayer.setConfig(APlayerAndroid.CONFIGID.HTTP_USER_AGENT, "User-Agent:" + userAgent);
                } else {
                    String value = headers.get(key);
                    stringBuilder.append(key).append(":").append(value).append("\r\n");
                }
            }
            aPlayer.setConfig(APlayerAndroid.CONFIGID.HTTP_CUSTOM_HEADERS, stringBuilder.toString());
        }
        Log.e("APlayer", "setUrl: " + path);
        this.path = path;

    }

    @Override
    public void setDataSource(AssetFileDescriptor fd) {
        Log.e("APlayer", "Open: " + fd.toString());
        aPlayer.open(fd.getFileDescriptor());
    }

    @Override
    public void start() {
        Log.e("APlayer", "start");
        aPlayer.play();
    }

    @Override
    public void pause() {
        Log.e("APlayer", "pause");
        aPlayer.pause();
    }

    @Override
    public void stop() {
        Log.e("APlayer", "stop");
        aPlayer.close();
    }

    @Override
    public void prepareAsync() {
        mPlayerEventListener.onPrepared();
        Log.e("APlayer", "prepareAsync:" + path);
        aPlayer.open(this.path);
        mPlayerEventListener.onPrepared();
    }

    @Override
    public void reset() {
        Log.e("APlayer", "reset");
    }

    @Override
    public boolean isPlaying() {
        return aPlayer.getState() == APlayerAndroid.PlayerState.APLAYER_PLAYING;
    }

    @Override
    public void seekTo(long time) {
        aPlayer.setPosition((int) time);
    }

    @Override
    public void release() {
        Log.e("APlayer", "release");
        aPlayer.close();
        aPlayer.destroy();
    }

    @Override
    public long getCurrentPosition() {
        return aPlayer.getPosition();
    }

    @Override
    public long getDuration() {
        return aPlayer.getDuration();
    }

    @Override
    public int getBufferedPercentage() {
        return aPlayer.getBufferProgress();
    }

    @Override
    public void setSurface(Surface surface) {
        Log.e("APlayer", "setSurface");
        aPlayer.setView(surface);
    }

    @Override
    public void setDisplay(SurfaceHolder holder) {
        Log.e("APlayer", "setDisplay");
        if (holder == null)
            setSurface(null);
        else
            setSurface(holder.getSurface());
    }

    @Override
    public void setVolume(float v1, float v2) {

    }

    @Override
    public void setLooping(boolean isLooping) {

    }

    @Override
    public void setOptions() {

    }

    @Override
    public void setSpeed(float speed) {
        aPlayer.setConfig(APlayerAndroid.CONFIGID.PLAY_SPEED, String.valueOf(speed * 100));
    }

    @Override
    public long getTcpSpeed() {
        return Long.valueOf(aPlayer.getConfig(APlayerAndroid.CONFIGID.DOWN_SPEED));
    }

    private APlayerAndroid.OnPlayCompleteListener onPlayCompleteListener = new APlayerAndroid.OnPlayCompleteListener() {
        @Override
        public void onPlayComplete(String s) {
            Log.e("APlayer", "onPlayComplete: " + s);
            switch (s) {
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_COMPLETE:
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_CLOSE:
                    mPlayerEventListener.onCompletion();
                    break;
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_OPENRROR:
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_CREATEGRAPHERROR:
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_READEFRAMERROR:
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_SEEKERROR:
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_HARDDECODERROR:
                case APlayerAndroid.PlayCompleteRet.PLAYRE_RESULT_DECODEERROR:
                    mPlayerEventListener.onError();
                    break;
            }
        }
    };

    private APlayerAndroid.OnBufferListener onBufferListener = new APlayerAndroid.OnBufferListener() {
        @Override
        public void onBuffer(int i) {
            mBufferedPercent = i;
            Log.e("APlayer", "OnBuffe: " + i);
        }
    };

    private APlayerAndroid.OnOpenCompleteListener onOpenCompleteListener = new APlayerAndroid.OnOpenCompleteListener() {
        @Override
        public void onOpenComplete(boolean b) {
            Log.e("APlayer", "OnOpenComplete: " + b);
            if (b) {
                mPlayerEventListener.onPrepared();
                int videoWidth = aPlayer.getVideoWidth();
                int videoHeight = aPlayer.getVideoHeight();
                if (videoWidth != 0 && videoHeight != 0) {
                    mPlayerEventListener.onVideoSizeChanged(videoWidth, videoHeight);
                }
                mPlayerEventListener.onInfo(3, 0);
            } else {
                mPlayerEventListener.onError();
            }
            aPlayer.play();
        }
    };
}
